package com.gouying.web.controller;

import com.alibaba.fastjson.TypeReference;
import com.gouying.common.constant.AuthServerConstant;
import com.gouying.common.utils.R;
import com.gouying.exception.BizCodeEnume;
import com.gouying.vo.MemberResponseVo;
import com.gouying.web.feign.MemberFeignService;
import com.gouying.web.feign.ThirdPartyFeignService;
import com.gouying.web.vo.UserLoginVo;
import com.gouying.web.vo.UserRegistVo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ly
 */
@Controller
@AllArgsConstructor(onConstructor_ = @Autowired)
public class LoginController {

    private final ThirdPartyFeignService thirdPartyFeignService;
    private final StringRedisTemplate redisTemplate;
    private final MemberFeignService memberFeignService;

    /**
     * 获取短信验证码
     *
     * @param phone 手机号
     * @return 发送验证码状态
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        //去Redis缓存中看看有没有验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        //如果缓存中有验证码
        if (!StringUtils.isEmpty(redisCode)) {
            //就获取缓存字符串中的时间，看看60s是否已过期0
            long l = Long.parseLong(redisCode.split("_")[1]);
            long interval = 60000;
            if (System.currentTimeMillis() - l < interval) {
                //60秒内不能再次发送验证码
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //缓存中没有验证码，就发送验证码
        //1、接口防刷
        //随机验证码
        String code = UUID.randomUUID().toString().substring(0, 5);
        //要放入redis中的拼接有系统时间的字符串
        String substring = code + "_" + System.currentTimeMillis();
        //2、验证码的再次校验，可以缓存在redis中key值是phone,value值是code
        System.out.println(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        //放入缓存，并设置过期时间等参数
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, substring, 10, TimeUnit.MINUTES);
        //远程调用第三方服务发送验证码
        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }


    /**
     * 用户注册
     *
     * @param vo                 用户注册入参
     * @param result             参数校验结果
     * @param redirectAttributes 重定向时携带参数
     * @return 重定向页面
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        //BindingResult result封装校验后的结果
        if (result.hasErrors()) {
            //获取校验出现的错误信息返回给前端
            Map<String, String> errors = result.getFieldErrors().stream().collect(
                    Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage)
            );
            redirectAttributes.addFlashAttribute("errors", errors);
            //Request method 'POST" not supported
            //校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //如果检验结果没错，就获取用户验证码执行注册功能
        String code = vo.getCode();
        //与缓存中的验证码进行对比
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            //验证码正确
            if (code.equals(s.split("_")[0])) {
                //删除缓存中验证码,令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过，真正的注册，调用远程会员服务进行注册功能
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    //远程调用成功跳转回登录界面
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    //远程调用失败
                    Map<String, String> errors = new HashMap<>();
                    //获取远程调用失败返回的错误信息，返回给前端
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
                //验证码不正确
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            //验证码失效了
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }


    /**
     * 访问登录页
     *
     * @param session 会话session
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            //用户没登录过
            return "login";
        } else {
            //登录过了
            return "redirect:http://gulimall.com";
        }
    }

    /**
     * 用户登录
     *
     * @param vo                 用户登录入参
     * @param redirectAttributes 重定向时携带参数
     * @param session            会话session
     * @return 跳转页面
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        //远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            //成功
            //拿到返回的数据
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {
            });
            //放入session
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
